import userEvent from '@testing-library/user-event'
import { message } from 'antd'
import axios, { AxiosResponse } from 'axios'
import { _sendMessageToChromeExtension } from './features/user/slice'

const Service = axios.create({
  baseURL: 'http://81.68.126.193:5000',
  timeout: 5000,
})

Service.interceptors.request.use(
  config => {
    let token = localStorage.getItem('token')
    if (token) {
      let header = config.headers
      if (header) {
        header['Authorization'] = `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  },
)

Service.interceptors.response.use(
  (response: AxiosResponse<Response<any>>) => {
    if (response.status != 200 && response.status != 201) {
      return Promise.reject(new Error(response.data.message))
    } else {
      return response
    }
  },
  error => {
    if (error.toString() === 'Error: Request failed with status code 401') {
      let token = localStorage.getItem('token')
      if (token) {
        message.error('登录凭证失效')
        localStorage.removeItem('token')
        _sendMessageToChromeExtension({ isLoginOut: true })
        window.location.reload()
      }
    }
    return Promise.reject(error)
  },
)

export default Service
